package main.com.cyz.LinkList.SingleLinkList;

import java.util.function.Consumer;

/**
 * @author fox
 * @version 1.0
 * @description 手写单向链表
 * @date 2024/5/17 10:02
 */
public class MySingleLinkList {

    private Node node;

    private static class Node{
        int value;
        Node nextNode;

        public Node(int value, Node nextNode) {
            this.value = value;
            this.nextNode = nextNode;
        }
    }

    public void addFirst(int num) {
        node = new Node(num,node);
    }

    public void showConsumer(Consumer<Integer> consumer){
        while (node != null){
            consumer.accept(node.value);
            node = node.nextNode;
        }
    }

    private Node findLastNode(){
        if (node == null){
            return null;
        }
        Node tempNode = node;
        while (tempNode.nextNode!=null){
            tempNode = tempNode.nextNode;
        }
        return tempNode;
    }

    public void addLast(int num) {
        if (findLastNode() != null) {
            findLastNode().nextNode = new Node(num, null);
        } else {
            addFirst(num);
        }
    }

    public int get(int index) {
        for (int i = 0; i < index; i++) {
            node = node.nextNode;
        }
        return node.value;
    }

}
